package com.example.demo.configuration;


import ch.qos.logback.classic.spi.ClassPackagingData;
import com.example.demo.entity.AllData;
import com.example.demo.entity.VirusData;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URI;
import java.nio.charset.StandardCharsets;

@Component
public class Config {

    public static AllData allData;
    @Scheduled(cron = "0 0 1 * * *")
    @PostConstruct
    void allData() throws IOException {
        String uriTemplate = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        //URI uri = UriComponentsBuilder.fromUriString(uriTemplate).build(42);

        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(uriTemplate))
                .headers(httpHeaders->httpHeaders.add("User-Agent","dgut"))
                .build();
        RestTemplate template = new RestTemplate();
        ResponseEntity<Resource> response = template.exchange(requestEntity, Resource.class);

        //String responseHeader = response.getHeaders().getFirst("MyResponseHeader");
        Resource body = response.getBody();
       // Reader in = new FileReader(url);
        assert body != null;
        Reader in=new InputStreamReader(body.getInputStream(), StandardCharsets.UTF_8);
        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);

        allData=new AllData();
        for (CSVRecord record : records) {
            String state = record.get("Province/State");
            String country = record.get("Country/Region");
            int num=0;
            for(int i=4;i<record.size()-1;i++) {
                num += Integer.parseInt(record.get(i));
            }
            VirusData virusData=new VirusData();
            virusData.setState(state);
            virusData.setCountry(country);
            virusData.setAllNum(num);
            allData.getAllVirusData().add(virusData);
            //System.out.println(columnOne+"-"+columnTwo+"-"+columnTwo1+"-"+columnTwo2);

        }
        System.out.println(allData.getAllVirusData().get(0));
        //alldata=allData;
    }
}
